package com.innovation.cmd;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 命令集合
 * @author Administrator
 *
 */
public class CommandSet {
	public static final CommandSet INSTANCE = new CommandSet();
	
	private Map<Integer, Command> cmdMap = new HashMap<Integer, Command>();
	
	/**
	 * 初始化所有命令
	 * @throws Exception
	 */
	public void init() throws Exception{
		Properties properties = new Properties();
		InputStream inputStream = null;
		try{
			inputStream = CommandSet.class.getClassLoader().getResourceAsStream("command.properties");
			properties.load(inputStream);
			for(Object key : properties.keySet()){
				String keyCode = String.valueOf(key); 
				String clazz = properties.getProperty(keyCode);
				if (clazz == null) {
					throw new Exception("command load exception: key=" + keyCode + "");
				}
				try {
					Command cmd = (Command) Class.forName(clazz).newInstance();
					cmdMap.put(Integer.valueOf(keyCode), cmd);
				} catch (Exception e) {
					throw new Exception("init class error:key=" + keyCode + ", class=" + clazz);
				}
			}
		}finally{
			if(inputStream != null){
				inputStream.close();
			}
		}
	}
	
	/**
	 * 获取命令
	 * @param cmdCode
	 * @return
	 */
	public Command getCommand(int cmdCode){
		return cmdMap.get(cmdCode);
	}
}
